package com.lagou.servlet;

import com.alibaba.fastjson.JSON;
import com.lagou.pojo.Result;
import com.lagou.service.AccountService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "accountServlet", urlPatterns = "/accountServlet")
public class AccountServlet extends HttpServlet {

    private AccountService accountService;

    /**
     * servlet单独有一个容器，归tomcat管理
     * @Autowired 无法注入 service
     */
    @Override
    public void init() throws ServletException {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        accountService = webApplicationContext.getBean("jdkProxy", AccountService.class);//动态代理 加入事务
        //accountService = (AccountService) webApplicationContext.getBean("accountService");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求体的字符编码
        request.setCharacterEncoding("UTF-8");

        String fromCardNo = request.getParameter("fromCardNo");
        String toCardNo = request.getParameter("toCardNo");
        String moneyStr = request.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {

            // 2. 调用service层方法
            int transfer = accountService.transfer(fromCardNo, toCardNo, money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        response.setContentType("application/json;charset=utf-8");
        Object o = JSON.toJSON(result);
        System.out.println(o);
        response.getWriter().print(o.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

